//
//  CommunitySelectVideoController.swift
//  TestDemo
//
//  Created by ayin on 2019/2/18.
//  Copyright © 2019 aYin. All rights reserved.
//

import UIKit

class CommunityVideoModel: NSObject {
    var thumbImg:UIImage = UIImage()
    var duration:Float = 0
    var size:Float = 0
    var asset:PHAsset = PHAsset.init()
}

class CommunitySelectVideoController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
    //MARK: - 声明属性
    //collection
    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets.init(top: 1, left: 1, bottom: 0, right: 1)
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: 92, height: 92)
        let collectionView = UICollectionView(frame: .zero,collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate   = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        if #available(iOS 11, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        collectionView.register(CommunitySelectVideoCell.self, forCellWithReuseIdentifier: CommunitySelectVideoCell.reuseId())
        return collectionView
    }()
    
    var videoLists:[CommunityVideoModel] = []

    //MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        getAllVideos()
    }
 
    //MARK: - 搭建UI
    func setupNav() {
        
    }
    
    func setupUI() {
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(collectionView)
        
        collectionView.frame = self.view.bounds
    }
    
    //MARK: - 数据
    func getAllVideos() {
        DispatchQueue.global().async {
            let options = PHFetchOptions.init()
            options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets(with: options)
 
            TZImageManager.default()?.getAssetsFrom(assetsFetchResults as? PHFetchResult<AnyObject>, allowPickingVideo: true, allowPickingImage: false, completion: { (models) in
                guard let videoModel = models else {return}
                videoModel.forEach({ (model) in
                    let  communityVideoModel = CommunityVideoModel()
                    
                    let videoAsset:PHAsset = model.asset
                    let manager = PHImageManager.default()
                    let videoOption = PHVideoRequestOptions()
                    videoOption.version = .current
                    videoOption.deliveryMode = .automatic
                    manager.requestAVAsset(forVideo: videoAsset, options: videoOption, resultHandler: { (asset, audioMix, info) in
                        guard let videoUrlAsset:AVURLAsset = asset as? AVURLAsset else {return}
                        let url = videoUrlAsset.url
                        url.relativePath.getFileSize({ (size,error) in
                            communityVideoModel.size = Float(size!/1024/1024)
                        })
                    })
                    
                    let imageOption = PHImageRequestOptions() //可以设置图像的质量、版本、也会有参数控制图像的裁剪
                    imageOption.isSynchronous = true
                    manager.requestImage(for: videoAsset, targetSize: CGSize.init(width: 200, height: 200), contentMode: .aspectFill, options: imageOption) { (thumbnailImage, info) in
                        communityVideoModel.thumbImg = thumbnailImage!
                    }
                    
                    communityVideoModel.asset = videoAsset
                    communityVideoModel.duration = Float(videoAsset.duration)
                    self.videoLists.append(communityVideoModel)
                })
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
            })
        }
    }
    
    //MARK: - 代理
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.videoLists.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CommunitySelectVideoCell.reuseId(), for: indexPath) as! CommunitySelectVideoCell
        if indexPath.row < self.videoLists.count {
            let model = self.videoLists[indexPath.row]
            cell.cellRefreshDatas(model)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row < self.videoLists.count {
            
        }
    }
}

class CommunitySelectVideoCell: UICollectionViewCell {
    //MARK: - 初始化
    //封面图
    lazy var videoThumbImgView: UIImageView = {
        let videoThumbImgView = UIImageView()
        videoThumbImgView.clipsToBounds = true
        videoThumbImgView.isUserInteractionEnabled = true
//        videoThumbImgView.contentMode = .scaleAspectFit
        return videoThumbImgView
    }()
    
    lazy var videoSizeLB : UILabel = {
        let videoSizeLB = UILabel()
        videoSizeLB.textAlignment = .left
        videoSizeLB.textColor = UIColor.white
        videoSizeLB.font = UIFont.systemFont(ofSize: 14)
        return videoSizeLB
    }()
    
    lazy var videoDurtionLB : UILabel = {
        let videoDurtionLB = UILabel()
        videoDurtionLB.textAlignment = .right
        videoDurtionLB.textColor = UIColor.white
        videoDurtionLB.font = UIFont.systemFont(ofSize: 14)
        return videoDurtionLB
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("视频播放cell: 释放")
    }
    
    static func reuseId() -> String {
        return NSStringFromClass(CommunitySelectVideoCell.self)
    }
    
    //MARK: - 搭建UI
    func setupUI() {
        contentView.backgroundColor = UIColor.black
        
        contentView.addSubview(videoThumbImgView)
        videoThumbImgView.frame = CGRect(x: 0, y: 0, width: 92, height: 92)
        
        contentView.addSubview(videoSizeLB)
        videoSizeLB.frame = CGRect(x: 10, y: 92-10-14, width: 100, height: 14)
        
        contentView.addSubview(videoDurtionLB)
        videoDurtionLB.frame = CGRect(x: 92-10-100, y: 92-10-14, width: 100, height: 14)
    }
    
    //MARK: - 刷新数据
    func cellRefreshDatas(_ data:CommunityVideoModel) {
        self.videoThumbImgView.image = data.thumbImg
        self.videoSizeLB.text = "\(data.size)"
        self.videoDurtionLB.text = "\(data.duration)"
    }
}


